<template>
	<view class="order_details safe_area">
		<image src="http://qianxueapplet.suoeryun.com/dingdan.png" class="order_details_img">
		</image>
		<view class="order_details_body">
			<view class="order_details_countdown">
				<view class="order_details_countdown_1">
					<!-- 待付款 -->
					<image v-if="orderInfo?.orderStatus === '1'" src="http://qianxueapplet.suoeryun.com/obligation.png">
					</image>
					<!-- 待发货 -->
					<image v-if="orderInfo?.orderStatus === '2'"
						src="http://qianxueapplet.suoeryun.com/tobeshipped.png"></image>
					<!-- 待收货 -->
					<image v-if="orderInfo?.orderStatus === '3'"
						src="http://qianxueapplet.suoeryun.com/tobereceived.png"></image>
					<!-- 待评价 -->
					<image v-if="orderInfo?.orderStatus === '4'" src="http://qianxueapplet.suoeryun.com/evaluate.png">
					</image>
					<!-- 交易取消 -->
					<image v-if="orderInfo?.orderStatus === '5'"
						src="http://qianxueapplet.suoeryun.com/exclamationcircle.png">
					</image>
					<view>
						<template v-if="orderInfo?.orderStatus === '1'">待付款</template>
						<template v-if="orderInfo?.orderStatus === '2'">待发货</template>
						<template v-if="orderInfo?.orderStatus === '3'">待收货 </template>
						<template v-if="orderInfo?.orderStatus === '4'"> 交易成功</template>
						<template v-if="orderInfo?.orderStatus === '5'">交易取消 </template>
					</view>
				</view>
				<view class="order_details_countdown_2">
					<!-- 待付款 -->
					<template v-if="orderInfo?.orderStatus === '1' && orderInfo?.countdown > 0">支付剩余
						<u-count-down :time="orderInfo?.countdown" format="DD:HH:mm" autoStart @change="onChange"
							ref="orderDetailCountDown">
							<view class="time">
								<text class="time__item">{{ timeData.minutes }}分</text>
								<text class="time__item">{{ timeData.seconds }}秒</text>
							</view>
						</u-count-down>
					</template>
					<!-- 待发货 -->
					<template v-if="orderInfo?.orderStatus === '2'">等待商家发货</template>
					<!-- 待收货 -->
					<template v-if="orderInfo?.orderStatus === '3'">请及时关注物流消息</template>
					<!-- 待评价 -->
					<template v-if="orderInfo?.orderStatus === '4'">
						<template v-if="orderInfo?.izEvaluate === '0'">给个五星好评吧!</template>
						<template v-else>感谢您的评价，祝您生活愉快！</template>
					</template>
					<!-- 交易取消 -->
					<template v-if="orderInfo?.orderStatus === '5'">
						交易已取消，请重新下单
					</template>
				</view>
			</view>
			<!-- 待付款/待收货/交易取消 -->
			<view class="submit_rder_info_address" @click.stop="handleEditAddressOrder"
				v-if="orderInfo?.orderStatus === '1' || orderInfo?.orderStatus === '2' || orderInfo?.orderStatus === '5'">
				<view class="submit_rder_info_address_title">
					<image src="http://qianxueapplet.suoeryun.com/dingwei.png"
						class="submit_rder_info_address_title_left"></image>
					<view class="submit_rder_info_address_title_right">
						<view class="submit_rder_info_address_title_right_left">
							<text>{{orderInfo?.consignee}}</text>
							<text>
								{{maskPhoneNumber(orderInfo?.phoneNumber)}}</text>
							<view class="submit_rder_info_address_body overflow">
								<template v-if="orderInfo?.location">
									{{orderInfo?.location?.replaceAll(',','')}}</template>
								{{orderInfo?.address}}
							</view>
						</view>
						<!-- 待付款 -->
						<u-icon name="arrow-right" size="12"
							v-if="orderInfo?.orderStatus === '1' || (orderInfo?.orderStatus === '2' && orderInfo?.izEditAddress === '0')"></u-icon>
					</view>
				</view>
			</view>
			<!-- 待收货 -->
			<view class="order_details_body_logistics" @click.stop="handleLogisticsDetails"
				v-if="orderInfo?.orderStatus === '3'">
				<view class="order_details_body_logistics_row">
					<view class="order_details_body_logistics_row_1 overflow">
						{{orderInfo?.AcceptStation??'还没有物流信息，耐心等待哦'}}
					</view>
					<view class="order_details_body_logistics_row_2">{{orderInfo?.AcceptTime}}</view>
				</view>
				<u-icon name="arrow-right" size="12"></u-icon>
			</view>
			<view class="submit_rder_info_goods">
				<view class="submit_rder_info_goods_title">商品信息</view>
				<view class="submit_rder_info_goods_body">
					<image :src="orderInfo?.goodsImages" class="submit_rder_info_goods_body_left"></image>
					<view class="submit_rder_info_goods_body_right">
						<view class="submit_rder_info_goods_body_right_top">
							<view class="submit_rder_info_goods_body_right_top_1">
								{{orderInfo?.goodsName}}
							</view>
							<view class="submit_rder_info_goods_body_right_top_2">
								<text class="submit_rder_info_goods_body_right_top_2_left"
									v-if="orderInfo?.specifications">{{orderInfo?.specifications}}</text>
								<text
									class="submit_rder_info_goods_body_right_top_2_right">x{{orderInfo?.orderNum}}</text>
							</view>
						</view>
						<view class="submit_rder_info_goods_body_right_btm">
							<view class="submit_rder_info_goods_body_right_btm_price goods_price18">
								<text>￥</text>{{orderInfo?.unitPrice}}
							</view>
						</view>
					</view>
				</view>
				<view class="submit_rder_info_goods_body_btn" v-if="orderInfo?.orderStatus === '4'">
					<button @click.stop="handleEvaluate" v-if="orderInfo?.izEvaluate === '0'">立即评价</button>
					<button @click.stop="handleEvaluateDetails" v-else>评价详情</button>
					<button @click.stop="handleAfterSale" v-if="orderInfo?.izApplyRefund === '1'">申请售后</button>
				</view>
			</view>
			<!-- 待付款 待发货 交易取消 -->
			<view class="order_details_body_info"
				v-if="orderInfo?.orderStatus === '1' || orderInfo?.orderStatus === '2' || orderInfo?.orderStatus === '5'">
				<view class="order_details_body_info_item">
					<text class="order_details_body_info_item_1">订单编号</text>
					<text class="order_details_body_info_item_2">{{orderInfo?.orderNo}}</text>
				</view>
				<view class="order_details_body_info_item">
					<text class="order_details_body_info_item_1">支付状态</text>
					<text class="order_details_body_info_item_2">
						<template v-if="orderInfo?.orderStatus === '2'">已支付</template>
						<template v-else>未支付</template>
					</text>
				</view>
				<view class="order_details_body_info_item">
					<text class="order_details_body_info_item_1">下单时间</text>
					<text class="order_details_body_info_item_2">{{orderInfo?.createTime}}</text>
				</view>
				<!-- 交易取消  -->
				<view class="order_details_body_info_item" v-if="orderInfo?.orderStatus === '5'">
					<text class="order_details_body_info_item_1">交易取消原因</text>
					<text class="order_details_body_info_item_2">{{orderInfo?.cancelCause}}</text>
				</view>
			</view>
			<view class="submit_rder_info_amount">
				<view class="submit_rder_info_amount_item">
					<text>商品金额</text>
					<view class="submit_rder_info_amount_item_right">
						￥{{(orderInfo?.unitPrice ?? 0) * (orderInfo?.orderNum ?? 0)}}
					</view>
				</view>
				<view class="submit_rder_info_amount_item">
					<text>运费</text>
					<view class="submit_rder_info_amount_item_right">
						<!-- <text class="submit_rder_info_amount_postage">商家包邮</text> -->
						<text>￥{{orderInfo?.freightCharges}}</text>
					</view>
				</view>
				<view class="submit_rder_info_amount_btm">
					<text>合计：</text>
					<view class="goods_price20">
						<text>￥</text>{{((orderInfo?.unitPrice??0) * (orderInfo?.orderNum ??0)) + (orderInfo?.freightCharges??0)}}
					</view>
				</view>
			</view>
			<!-- 待收货 交易成功-->
			<view class="order_details_orderinfo submit_rder_info_goods"
				v-if="orderInfo?.orderStatus === '3' || orderInfo?.orderStatus === '4'">
				<view class="submit_rder_info_goods_title">订单信息</view>
				<view class="order_details_orderinfo_item">
					<text class="order_details_orderinfo_item_1">收货信息</text>
					<view class="order_details_orderinfo_item_2">
						<view>
							<text>{{orderInfo?.consignee}}</text><text>{{maskPhoneNumber(orderInfo?.phoneNumber)}}</text>
						</view>
						<view><template v-if="orderInfo?.location">
								{{orderInfo?.location?.replaceAll(',','')}}</template>
							{{orderInfo?.address}}
						</view>
					</view>
				</view>
				<view class="order_details_orderinfo_item">
					<text class="order_details_orderinfo_item_1">订单编号</text>
					<view class="order_details_orderinfo_item_2">
						{{orderInfo?.orderNo}}
					</view>
				</view>
				<view class="order_details_orderinfo_item">
					<text class="order_details_orderinfo_item_1">下单时间</text>
					<view class="order_details_orderinfo_item_2">
						{{orderInfo?.createTime}}
					</view>
				</view>
				<view class="order_details_orderinfo_item">
					<text class="order_details_orderinfo_item_1">支付时间</text>
					<view class="order_details_orderinfo_item_2">
						{{orderInfo?.payTime}}
					</view>
				</view>
				<view class="order_details_orderinfo_item">
					<text class="order_details_orderinfo_item_1">订单总额</text>
					<view class="order_details_orderinfo_item_2">
						{{orderInfo?.amountPayable}}
					</view>
				</view>
				<view class="order_details_orderinfo_item">
					<text class="order_details_orderinfo_item_1">商品总额</text>
					<view class="order_details_orderinfo_item_2">
						{{orderInfo?.totalPrice}}
					</view>
				</view>
				<view class="order_details_orderinfo_item">
					<text class="order_details_orderinfo_item_1">运费金额</text>
					<view class="order_details_orderinfo_item_2">
						{{orderInfo?.freightCharges}}
					</view>
				</view>
				<view class="order_details_orderinfo_item">
					<text class="order_details_orderinfo_item_1">备注</text>
					<view class="order_details_orderinfo_item_2">
						{{orderInfo?.remark}}
					</view>
				</view>
			</view>
		</view>
		<view class="order_details_body_btm btm_btm safe_area">
			<view class="btm_btm_row order_details_body_btm_row"
				v-if="orderInfo?.orderStatus === '1' || orderInfo?.orderStatus === '2' || orderInfo?.orderStatus === '3'">
				<!-- 待付款 -->
				<template v-if="orderInfo?.orderStatus === '1'">
					<button class="default" @click.stop="handleCancelOrder">取消订单</button>
					<button @click.stop="handlePay">去支付</button>
				</template>
				<!-- 待发货 -->
				<template v-if="orderInfo?.orderStatus === '2'">
					<button class="default" @click.stop="handleAfterSale">申请售后</button>
					<button @click.stop="handleEditAddressOrder" :disabled="orderInfo?.izEditAddress === '1'">修改地址
					</button>
				</template>
				<!-- 待收货 -->
				<template v-if="orderInfo?.orderStatus === '3'">
					<button class="default" @click.stop="handleLogisticsDetails ">查看物流</button>
					<button @click.stop=" handleConfirmReceipt">确认收货 </button>
				</template>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { onMounted, onUnmounted, ref, unref } from 'vue';
	import { onLoad } from '@dcloudio/uni-app';
	import { qxGoodsOrderQueryById, cancelOrder, requestPayment, confirmReceipt, getBusinessOrderHandle, editAddress } from '@/config/goodStuff.api';
	import { maskPhoneNumber } from '@/util/index';
	import { onShow, onHide } from '@dcloudio/uni-app';

	const timeData = ref({ minutes: 0, seconds: 0, });
	const orderInfo = ref();
	const orderDetailCountDown = ref();

	onShow(async () => {
		await loadData();
	})

	onHide(() => {
		if (orderDetailCountDown.value) {
			orderDetailCountDown.value.pause();
		}
	})

	onLoad(async (params) => {
		console.log(params, 'params');
		orderInfo.value = params;
	})

	onMounted(() => {
		// 修改地址监听
		uni.$on('selectAddress', async (item) => {
			const pages = getCurrentPages();
			const currentRoute = pages[pages.length - 1].route;
			if (currentRoute === 'pages/goodStuff/orderDetails') {
				// 修改地址接口
				const res = await editAddress({ id: item?.orderId, location: item?.location, locationCode: item?.locationCode, address: item?.address, phoneNumber: item?.phoneNumber, consignee: item?.consignee, freightCharges: item?.freightCharges });
				uni.showToast({
					icon: 'success',
					title: res
				})
				orderInfo.value.location = item?.location;//收货地区
				orderInfo.value.locationCode = item?.locationCode;//收货地区code
				orderInfo.value.address = item?.address;//收货详情地址
				orderInfo.value.phoneNumber = item?.phoneNumber;//收货人手机号码
				orderInfo.value.consignee = item?.consignee;//收货人名称
				orderInfo.value.freightCharges = item?.freightCharges;//收货人名称
				if (orderInfo.value?.orderStatus === '2') {//待发货
					orderInfo.value.izEditAddress = '1';//是否修改地址
				}
				uni.$emit('orderDetails');
			}
		})
	})

	onUnmounted(() => {
		// 销毁修改地址监听
		uni.$off('selectAddress')
	})

	async function loadData() {
		const params = unref(orderInfo)
		const res = await qxGoodsOrderQueryById({ id: params?.id });
		orderInfo.value = { ...params, ...res };
		if (orderInfo.value?.orderStatus === '3') {
			// 查询物流信息
			const res = await getBusinessOrderHandle({ trackType: '1', logisticCode: orderInfo.value?.logisticCode, shipperCode: orderInfo.value?.shipperCode, orderId: orderInfo.value?.id });
			res?.Traces?.reverse();
			if (res?.Traces?.length > 0) {
				orderInfo.value.AcceptStation = res?.Traces[0].AcceptStation;
				orderInfo.value.AcceptTime = res?.Traces[0].AcceptTime;
			}
			uni.setStorageSync('logistics', res);
		}
	}

	/**
	 * 倒计时 监听
	 */
	function onChange(e) {
		timeData.value = e;
	}

	/**
	 * 取消订单
	 */
	function handleCancelOrder() {
		uni.showModal({
			content: '是否取消该订单？',
			confirmColor: '#FF943C',
			success: async (res) => {
				if (res?.confirm) {
					uni.showLoading()
					const res = await cancelOrder({ cancelType: '1', id: unref(orderInfo)?.id });
					uni.showToast({
						icon: 'success',
						title: res,
						success() {
							loadData();
							uni.$emit('orderDetails');
						}
					})

				} else { }
			},
			fail: (res) => {
				console.log(res, 'sdf');
			}
		})
	}

	/**
	 * 支付
	 */
	async function handlePay() {
		const res = await requestPayment({ id: orderInfo.value?.id });
		//#ifdef MP-WEIXIN
		uni.requestPayment({
			provider: 'wxpay',
			orderInfo: {},
			timeStamp: res?.timeStamp,//时间戳从1970年1月1日至今的秒数，即当前的时间。
			nonceStr: res?.nonceStr,//随机字符串，长度为32个字符以下。
			package: res?.packageVal,//统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=xx。
			signType: res?.signType,//签名算法，应与后台下单时的值一致
			paySign: res?.paySign,//签名，具体签名方案参见
			success: function (res) {
				loadData();
				uni.$emit('orderDetails');
			},
			fail: function (err) {
				console.log('fail:' + JSON.stringify(err));
			}
		});
		//#endif

	}

	/**
	 * 申请售后/再次申请
	 */
	function handleAfterSale() {
		const item = unref(orderInfo);
		uni.$u.route('/pages/goodStuff/afterSale', {
			orderId: item?.id,
		});
	}

	/**
	 * 去评价
	 */
	function handleEvaluate() {
		const item = unref(orderInfo);
		uni.$u.route('/pages/goodStuff/evaluate', {
			orderId: item?.id,
			goodsId: item?.goodsId,
			goodsName: item?.goodsName,
		});
	}

	/**
	 * 评价详情
	 */
	function handleEvaluateDetails() {
		const item = unref(orderInfo);
		uni.$u.route('/pages/goodStuff/evaluateDetails', {
			id: item?.id,
		});
	}

	/**
	 * 修改地址
	 */
	function handleEditAddressOrder() {
		const item = unref(orderInfo);
		console.log(item, 'item');
		// 待付款
		if (orderInfo.value?.orderStatus !== '5') {
			uni.$u.route('/pages/goodStuff/selectAddress', {
				orderStatus: item?.orderStatus,
				freightTemplateId: item?.freightTemplateId || item?.templateId,
				orderId: item?.id
			});
		}
	}


	/**
	 * 物流详情
	 */
	function handleLogisticsDetails() {
		const item = unref(orderInfo)
		uni.$u.route('/pages/goodStuff/logisticsDetails', {
			logisticCode: item?.logisticCode,
			shipperCode: item?.shipperCode,
			orderId: item?.id,
			address: `${item?.location ? item?.location?.replaceAll(',', '') : ''}${item?.address}`,
			orderNo: item?.orderNo,
		});
	}


	/**
	 * 确认收货
	 */
	function handleConfirmReceipt() {
		uni.showModal({
			content: '是否确认收货？',
			confirmColor: '#FF943C',
			success: async (res) => {
				if (res?.confirm) {
					uni.showLoading()
					const res = await confirmReceipt({ id: orderInfo.value?.id });
					uni.showToast({
						icon: 'success',
						title: res,
						success() {
							loadData();
							uni.$emit('orderDetails');
						}
					})
				} else { }
			},
			fail: (res) => {
				console.log(res, 'sdf');
			}
		})
	}
</script>

<style lang="scss" scoped>
	.order_details {
		.order_details_img {
			height: 4rpx;
			display: block;
			width: 100vw;
		}

		.order_details_body {
			padding: 24rpx 24rpx 74rpx 24rpx;

			// 待付款 倒计时
			.order_details_countdown {
				border-radius: 12rpx;
				background-color: #FF943C;
				padding: 24rpx;
				color: #fff;
				margin-bottom: 20rpx;

				.order_details_countdown_1 {
					font-size: 36rpx;
					font-weight: 500;
					display: flex;
					align-items: center;
					margin-bottom: 12rpx;

					image {
						width: 48rpx;
						height: 48rpx;
						margin-right: 8rpx;
					}
				}

				.order_details_countdown_2 {
					display: flex;
					align-items: center;
					font-size: 28rpx;
				}
			}

			// 待收货 物流信息
			.order_details_body_logistics {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.order_details_body_logistics_row {
					flex: 1;
					padding-right: 52rpx;

					.order_details_body_logistics_row_1 {
						font-size: 32rpx;
						color: #FF943C;
						margin-bottom: 18rpx;
						width: calc(100vw - 48rpx - 36px - 52rpx);
					}

					.order_details_body_logistics_row_2 {
						font-size: 28rpx;
						color: #9E9E9E;
					}
				}
			}

			// 商品信息
			.submit_rder_info_goods {
				.submit_rder_info_goods_body_btn {
					display: flex;
					justify-content: flex-end;
					padding-top: 24rpx;

					button {
						margin: 0;
						padding: 0 30rpx;
						height: 60rpx;
						line-height: 58rpx;
						border: 2rpx solid #FF3535;
						color: #FF3535;
						background-color: #fff;
						font-size: 28rpx;
						border-radius: 98rpx;
						margin-right: 24rpx;

						&[disabled]:not([type]) {
							opacity: 0.5;
						}

						&:last-child {
							margin-right: 0;
						}

						&::after {
							border: 0;
						}
					}
				}
			}

			// 信息
			.order_details_body_info {

				.order_details_body_info_item {
					margin-bottom: 24rpx;
					font-size: 30rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;

					&:last-child {
						margin-bottom: 0;
					}

					.order_details_body_info_item_1 {
						color: #333333;
					}

					.order_details_body_info_item_2 {
						color: #000000;
					}
				}
			}

			// 订单信息
			.order_details_orderinfo {
				.order_details_orderinfo_item {
					display: flex;
					align-items: flex-start;
					font-size: 28rpx;
					padding-top: 24rpx;

					.order_details_orderinfo_item_1 {
						width: 140rpx;
						color: #666666;
					}

					.order_details_orderinfo_item_2 {

						&>view {
							padding-bottom: 12rpx;

							&:last-child {
								padding-bottom: 0;
							}
						}
					}
				}
			}
		}

		.order_details_body_btm {
			.order_details_body_btm_row {
				button {
					width: 160rpx;
					margin-right: 24rpx;

					&:last-child {
						margin-right: 0;
					}
				}
			}
		}
	}
</style>